package com.mrtan.config;

/**
 * @author 李聪
 * @version 2023/12/6
 */

import cn.dev33.satoken.SaManager;
import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.filter.SaServletFilter;
import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaHttpMethod;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpInterface;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import cn.hutool.core.convert.Convert;
import com.mrtan.bean.Account;
import com.mrtan.bean.Permission;
import com.mrtan.bean.Role;
import com.mrtan.service.AccountService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.*;

/**
 * @author 李聪
 * @version 2023/11/28
 */
@Configuration
public class SaTokenConfigure implements WebMvcConfigurer {
    @Bean
    public SaServletFilter getSaServletFilter() {
        return new SaServletFilter()
                // 指定 [拦截路由] 与 [放行路由]
                .addInclude("/**").addExclude("/favicon.ico")
                // 认证函数: 每次请求执行
                .setAuth(obj -> {
                    SaManager.getLog().debug("----- 请求path={}  提交token={}", SaHolder.getRequest().getRequestPath(), StpUtil.getTokenValue());
                    // ...
                })
                // 异常处理函数：每次认证函数发生异常时执行此函数
                .setError(e -> {
                    return SaResult.error(e.getMessage());
                })
                // 前置函数：在每次认证函数之前执行
                .setBeforeAuth(obj -> {
                    SaHolder.getResponse()
                            // ---------- 设置跨域响应头 ----------
                            // 允许指定域访问跨域资源
                            .setHeader("Access-Control-Allow-Origin", "*")
                            // 允许所有请求方式
                            .setHeader("Access-Control-Allow-Methods", "*")
                            // 允许的header参数
                            .setHeader("Access-Control-Allow-Headers", "*")
                            // 有效时间
                            .setHeader("Access-Control-Max-Age", "3600")
                    ;
                    // 如果是预检请求，则立即返回到前端
                    SaRouter.match(SaHttpMethod.OPTIONS)
                            .free(r -> System.out.println("--------OPTIONS预检请求，不做处理"))
                            .back();
                })
                ;
    }

    // 注册 Sa-Token 拦截器，打开注解式鉴权功能
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册 Sa-Token 拦截器，打开注解式鉴权功能
        registry.addInterceptor(new SaInterceptor()).addPathPatterns("/**");
    }

    @Bean
    public StpInterface getStpInterface(AccountService accountService) {
        return new StpInterface() {
            /**
             * @param o 当前账号id
             * @param s 当前账号类型标识
             * @return {@link List}<{@link String}>
             */
            @Override
            public List<String> getPermissionList(Object o, String s) {
                //得到当前登录用户的权限列表
                Integer id = Convert.toInt(o);
                if (id != null) {
                    Account account = accountService.findById((id));
                    Set<Role> roles = account.getRoles();
                    Set<String> permissions = new HashSet<>();
                    if (roles != null) {
                        for (Role role : roles) {
                            Set<Permission> permissionSet = role.getPermissions();
                            for (Permission permission : permissionSet) {
                                permissions.add(permission.getCode());
                            }
                        }
                    }
                    return new ArrayList<>(permissions);
                }
                return Collections.emptyList();
            }

            @Override
            public List<String> getRoleList(Object o, String s) {
                //得到当前登录用户的角色列表
                Integer id = Convert.toInt(o);
                if (id != null) {
                    Account account = accountService.findById((id));
                    Set<Role> roles = account.getRoles();
                    Set<String> roleCodes = new HashSet<>();
                    if (roles != null) {
                        for (Role role : roles) {
                            roleCodes.add(role.getCode());
                        }
                    }
                    return new ArrayList<>(roleCodes);
                }
                return Collections.emptyList();
            }
        };
    }
}

